package com.dalanmao.netty2;

import android.content.Intent;
import android.util.Log;

import java.io.UnsupportedEncodingException;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * Created by MENRED-WHB on 2016/10/28.
 */

public class NettyClientHandler extends ChannelInboundHandlerAdapter {


    public static final String TAG = "NettyClientHandler";


    /**
     * 局域网  处理粘包
     *
     * @param str
     */
    void handleStick(String str) {

        if (!str.contains("}{")) {   ///不包含

//
            Log.i("zl", "不需粘包处理：" + str);


        } else {
            int ind = str.indexOf("}{");

            String fir = str.substring(0, ind + 1);
            String left = str.substring(ind + 1, str.length());
            handleStick(left);

            Log.i("zl", "粘包处理：" + str);
        }
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);


        try {
            String body = new String(yiHuo(req), "utf-8");

            handleStick(body);

//            Log.i(TAG, "channelRead: " + body);


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
            throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {
                ctx.close();
                System.out.println("READER_IDLE 读超时");
            } else if (e.state() == IdleState.WRITER_IDLE) {
                ByteBuf buff = ctx.alloc().buffer();
                buff.writeBytes("mayi test".getBytes());
                ctx.writeAndFlush(buff);
                System.out.println("WRITER_IDLE 写超时");
            }
        }
    }


    public byte[] yiHuo(byte[] k) {
        byte[] tem = new byte[k.length];
        for (int i = 0; i < k.length; i++) {
            tem[i] = (byte) (k[i] ^ 0xa1);
        }
        return tem;
    }


    /**
     * 心跳任务
     */
    private class HearBeatTask implements Runnable {

        private ChannelHandlerContext ctx = null;


        public HearBeatTask(final ChannelHandlerContext ctx) {
            this.ctx = ctx;
        }

        @Override
        public void run() {


            String heatBeat = "";
            ctx.writeAndFlush(heatBeat);

        }
    }


}
